package chunmap.service.gmap;

import java.awt.Image;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import chunmap.service.Service;
import chunmap.util.image.ImageUtil;
import chunmap.view.layer.Layer;

public class GMService implements Service {
	
	private static final String defaultFormat = "png";
	private GetTileHelper getTileHelper;
	private GetFeatureInfo getInfo;

	public GMService(List<Layer> layers) {
		getTileHelper = new GetTileHelper(layers);
		getInfo= new GetFeatureInfo(layers);
	}

	@Override
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, java.io.IOException {
		
		String requestStr = request.getParameter("REQUEST");
		if (requestStr != null) {
			if (requestStr.equalsIgnoreCase("GetFeatureInfo")) {
				getInfo.service(request, response);
				return;
			}
		} else {

			int x = Integer.valueOf(request.getParameter("x"));
			int y = Integer.valueOf(request.getParameter("y"));
			int z = Integer.valueOf(request.getParameter("z"));

			Image image = getTileHelper.getImage(x, y, z);

			if (image != null) {
				fireImage(image, response);
			}
		}
	}
	
	private void fireImage(Image image,HttpServletResponse response) throws IOException{
		PrintStream out = new PrintStream(response.getOutputStream());
		byte[] data=ImageUtil.Image2ByteArray(image, defaultFormat);
		out.write(data);
	}
}
